package cn.yll.api.util;

import cn.yll.common.exception.BsErrEnum;
import cn.yll.common.exception.BsException;
import cn.yll.common.utils.CommonUtil;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.SecureRandom;

/**
 * Created by yangll on 2020/5/20 0020.
 * @author yangll
 */
public final class VerifyCodeUtil {
    /**
     * 图片宽
     */
    private static final int width = 100;
    /**
     * 图片高
     */
    private static final int height = 40;
    /**
     * 干扰线数量
     */
    private static final int lineSize = 15;
    /**
     * 随机产生字符数量
     */
    private static final int stringNum = 4;

    /**
     * 字体表
     */
    private static final String[] fonts = new String[]{Font.MONOSPACED, Font.DIALOG_INPUT, Font.DIALOG, Font.SERIF, Font.SANS_SERIF};

    private static final SecureRandom random = new SecureRandom();

    /**
     * 获得颜色
     */
    private static Color getRandomColor() {
        return new Color(random.nextInt(235), random.nextInt(235), random.nextInt(235));
    }

    private static Font getRandomFont() {
        //0无样式 1粗体 2斜体 3粗斜体
        //随机字体，随机样式，随机大小
        return new Font(fonts[random.nextInt(fonts.length)], random.nextInt(4), random.nextInt(15) + 23);
    }

    /**
     * 生成随机图片
     */
    public static String getRandomCode(HttpServletResponse response) {
        // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        // 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
        Graphics g = image.getGraphics();
        //图片大小
        g.fillRect(0, 0, width, height);
        //字体大小
        g.setFont(new Font("Times New Roman", Font.PLAIN, 20));
        // 绘制干扰线
        for (int i = 0; i < lineSize; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(13);
            int yl = random.nextInt(15);
            //字体颜色
            g.setColor(getRandomColor());
            g.drawLine(x, y, x + xl, y + yl);
        }
        // 绘制随机字符
        String randomString = CommonUtil.randomStr(stringNum);
        for (int i = 0; i < stringNum; i++) {
            g.setFont(getRandomFont());
            g.setColor(getRandomColor());
            g.translate(random.nextInt(3), random.nextInt(3));
            g.drawString(String.valueOf(randomString.charAt(i)), 10 + (i * 20), random.nextInt(15) + 15);
        }
        g.dispose();
        try {
            // 将内存中的图片通过流动形式输出到客户端
            ImageIO.write(image, "JPEG", response.getOutputStream());
        } catch (IOException e) {
            throw new BsException(BsErrEnum.UNKNOWN_ERROR);
        }
        return randomString;
    }
}
